package cn.ztelovecly.springboot.framework.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpUtil {

    public static String get(String url) throws Exception{

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpgets = new HttpGet(url);
        try {
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);
            HttpResponse response = httpclient.execute(httpgets);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // 将流转化为字符串后输出
                return convertStreamToString(entity.getContent());
            }
        }catch(Exception ex){
            ex.printStackTrace();
            throw ex;
        }finally {
            httpgets.abort();
        }
        return "";
    }

    public static String post(String url, Map<String,String> formData) throws Exception{

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = formatFormData(url, formData);
        try {
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // 将流转化为字符串后输出
                return convertStreamToString(entity.getContent());
            }
        }catch(Exception ex){
            ex.printStackTrace();
            throw ex;
        }finally {
            httpPost.abort();
        }
        return "";
    }



    public static String get(String url,Map<String,String> param) throws Exception{

        StringBuilder stringBuilder = new StringBuilder("");
        Set<String> paramKeyList;
        String fullUrl = url;
        // 如果参数不为空，则把参数拼成queryString传递给get(url)方法
        if(param!=null && param.size()>0) {
            stringBuilder.append("?");
            paramKeyList = param.keySet();
            for(String paramKey : paramKeyList){
                stringBuilder.append(paramKey).append("=").append(param.get(paramKey)).append("&");
            }
            String queryString = stringBuilder.toString();
            // 去除最后一个"&"符号
            queryString = queryString.substring(0, queryString.length() - 1);
            fullUrl += queryString;
        }
        return get(fullUrl);
    }

    public static String post(String url,Map<String,String> queryParams,Map<String,String> formData) throws Exception{

        StringBuilder stringBuilder = new StringBuilder("");
        Set<String> paramKeyList;
        String fullUrl = url;
        // 如果参数不为空，则把参数拼成queryString传递给get(url)方法
        if(queryParams!=null && queryParams.size()>0) {
            stringBuilder.append("?");
            paramKeyList = queryParams.keySet();
            for(String paramKey : paramKeyList){
                stringBuilder.append(paramKey).append("=").append(queryParams.get(paramKey)).append("&");
            }
            String queryString = stringBuilder.toString();
            // 去除最后一个"&"符号
            queryString = queryString.substring(0, queryString.length() - 1);
            fullUrl += queryString;
        }
        return post(fullUrl, formData);
    }

    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private static HttpPost formatFormData(String url, Map<String, String> params){

        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        Set<String> keySet = params.keySet();
        for(String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return httpost;
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}
